Ext.define('AgenteNET.controller.utilitarios.Papeis', {
	extend : 'Ext.app.Controller',
	stores:['utilitarios.Papeis'],
	models:['utilitarios.Papel','utilitarios.Funcao','utilitarios.UsuarioPorPapel'],
	views:['utilitarios.papeis.Listar','utilitarios.papeis.Novo','utilitarios.papeis.Editar'],
	init : function() {
		this.control({
		});
		this.inicializado = true;
	},
	Listar:function(el){
		return Ext.create('AgenteNET.view.utilitarios.papeis.Listar');
	},
	
	loadTree:function(form,id){
		if(id==undefined)id='';
		form.down('treepanel[recurso="funcoes"]').getStore().setProxy({
			type : 'rest',
			url : '/agentenet/public/utilitarios/Papeis/'+id,
			extraParams : {
				tree : 'funcoes',
			},
			reader : {
				type : 'json',
				root : 'data',
			},
		});
		form.down('treepanel[recurso="funcoes"]').store.load();
		form.down('treepanel[recurso="usuarios"]').getStore().setProxy({
			type : 'rest',
			url : '/agentenet/public/utilitarios/Papeis/'+id,
			extraParams : {
				tree : 'usuarios',
			},
			reader : {
				type : 'json',
				root : 'data',
			},
		});
		form.down('treepanel[recurso="usuarios"]').store.load();
		return form;
	},
	
	Novo : function(el) {
		var form=this.loadTree(Ext.create('AgenteNET.view.utilitarios.papeis.Novo'));
		form.loadRecord(this.getStore('utilitarios.Papeis').model.create({}));
		return form;
	},
	Editar : function(el,model) {
		var form=this.loadTree(Ext.create('AgenteNET.view.utilitarios.papeis.Editar'),model.get('id'));
		form.loadRecord(model);
		return form;
	},
	Adicionar: function(el){
		var form=el.up('form'),win=el.up('window'),model=form.getRecord();
		if(!form.getForm().isValid())return false;
		model.set(form.getValues());
		var ope={
		    win:win,
		    elform:form,
		    model:model,
			success:function(el,op){
				var b;if(op.win)if(b=op.win.down('button[text="Fechar"]'))b.fireEvent('click',b);
		    	if(op.elform.up('panel[chamadoPor]'))
		    		if(op.elform.up('panel[chamadoPor]').chamadoPor){
		    			if(form.up('panel[chamadoPor]').chamadoPor.up('grid')){
		    				if(form.up('panel[chamadoPor]').chamadoPor.up('grid').store){
								b=form.up('panel[chamadoPor]').chamadoPor.up('grid').store;
								b.load();
		    				}
						}
					}
			},
		    failure: function() {
			       console.log(arguments);
		    },
		}
		
		var records = el.up('form').down('treepanel[recurso="usuarios"]').getView().getChecked();
        usuarios = [];
	    Ext.Array.each(records, function(rec){
	        usuarios.push(rec.get('id'));
	    });
		model.getProxy().setExtraParam('usuarios',Ext.encode(usuarios));

		var records = el.up('form').down('treepanel[recurso="funcoes"]').getView().getChecked();
        funcoes = [];
	    Ext.Array.each(records, function(rec){
	        funcoes.push(rec.get('id'));
	    });
		model.getProxy().setExtraParam('funcoes',Ext.encode(funcoes));

		model.save(ope);
		return model;
	},
	Salvar: function(el){
		var form=el.up('form'),win=el.up('window'),model=form.getRecord();
		if(!form.getForm().isValid())return false;
		model.set(form.getValues());
		
		var ope={
		    win:win,
		    elform:form,
		    model:model,
			success:function(el,op){
				var b;if(op.win)if(b=op.win.down('button[text="Fechar"]'))b.fireEvent('click',b);
		    	if(op.elform.up('panel[chamadoPor]'))
		    		if(op.elform.up('panel[chamadoPor]').chamadoPor){
		    			if(form.up('panel[chamadoPor]').chamadoPor.up('grid')){
		    				if(form.up('panel[chamadoPor]').chamadoPor.up('grid').store){
								b=form.up('panel[chamadoPor]').chamadoPor.up('grid').store;
								b.load();
		    				}
						}
					}
			},
		    failure: function() {
			       console.log(arguments);
		    },
		}
		
		var records = el.up('form').down('treepanel[recurso="usuarios"]').getView().getChecked();
        usuarios = [];
	    Ext.Array.each(records, function(rec){
	        usuarios.push(rec.get('id'));
	    });
		model.getProxy().setExtraParam('usuarios',Ext.encode(usuarios));

		var records = el.up('form').down('treepanel[recurso="funcoes"]').getView().getChecked();
        funcoes = [];
	    Ext.Array.each(records, function(rec){
	        funcoes.push(rec.get('id'));
	    });
		model.getProxy().setExtraParam('funcoes',Ext.encode(funcoes));
		
		model.save(ope);
		return model;
	},
	Excluir: function(el){
		var win=null,form=null,records=[],storeGrid=null,storeTree=null;
		if(el.up('form')){
			form=el.up('form');
			win=el.up('window');
			records[0]=el.up('form').getRecord();
		}else if(el.up('grid')){
			console.log(el.up('grid').up('panel'));
			records=el.up('grid').getSelectionModel().getSelection();
			storeGrid=el.up('grid').store;
		}
		if(records.length==0){
			Ext.MessageBox.show({
		           title: 'Exclusão de Papeis',
		           msg: 'Nenhuma registro de papel foi selecionada para exclusão',
		           buttons: Ext.MessageBox.OK,
		           animateTarget: el,
		           icon: Ext.MessageBox.ERROR
			});
		}
		if(records.length>0){
			Ext.MessageBox.confirm({
		           title: 'Exclusão de ações',
		           msg:'Confirma a'+(records.length>1?'s':'')+' exclus'+(records.length>1?'ões':'ão')+' do'+(records.length>1?'s':'')+' pape'+(records.length>1?'is':'l')+' '+(records.length>1?'selecionadas':''),
		           icon: Ext.MessageBox.QUESTION,
		           buttons: Ext.MessageBox.YESNO,
 		           animateTarget: el,
		            buttonText:{ 
		                yes: "Sim", 
		                no	: "Não" 
		            },
		            scope:this,
		            fn: function(resposta){
		            	if(resposta=='yes'){
	            			if(storeGrid){
	            				storeGrid.clearFilter();
		            			storeGrid.remove(records);
		            			storeGrid.sync();
		            		}else{
		            			form.submit({
		            			    clientValidation: true,
		            			    url: records[0].getProxy().url+'/id/'+records[0].get('id'),
		            			    method:'POST',
		            			    params:{_method:'delete'},
		            			    win:win,
		            			    elform:form,
		            			    success: function(form, op) {
		            					var b;if(op.win)if(b=op.win.down('button[text="Fechar"]'))b.fireEvent('click',b);
		            					if(op.elform.up('panel[chamadoPor]'))
		            			    		if(op.elform.up('panel[chamadoPor]').chamadoPor){
		            			    			if(op.elform.up('panel[chamadoPor]').chamadoPor.store){
	            									b=op.elform.up('panel[chamadoPor]').chamadoPor.store;
	            									b.load();
		            							}
		            						}
		            			    },
		            			    failure: function(form, action) {
		            				       console.log(arguments);
		            			    }
		            			});
		            		}
		            	}
		            }
			});
		}
		return records;
	},
});
